﻿using System.Collections.Generic;
using AspectCore.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using NetMicro.Core.Helper;
using System;
using System.Linq;
using System.Reflection;
using NetMicro.HttpClient.Proxies;
using System.Net;

namespace NetMicro.HttpClient.AspectExtend
{
    /// <summary>
    /// 添加远程服务发现注册
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册服务发现远程请求
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddHttpProxy(this IServiceCollection services)
        {
            List<System.Reflection.Assembly> assemblys = ReflectionHelper.Load();
            foreach (Assembly assembly in assemblys)
            {
                foreach (var item in assembly.GetTypes())
                {
                    if (item.IsInterface && item.GetTypeInfo().ImplementedInterfaces.Any(m => m == typeof(IHttpServiceBusProxy)))
                    {
                        services.AddSingleton(item, provider =>
                        {
                            return provider.GetService<IProxyGenerator>().CreateInterfaceProxy(item);
                        });
                    }
                    if (item.IsInterface && item.GetTypeInfo().ImplementedInterfaces.Any(m => m == typeof(IHttpProxy)))
                    {
                        services.AddSingleton(item, provider =>
                        {
                            return provider.GetService<IProxyGenerator>().CreateInterfaceProxy(item);
                        });
                    }
                }
            }
            return services;
        }


    }
}
